#!/bin/bash
# Harbor自动垃圾回收配置脚本
# 支持从环境变量或配置文件读取配置

set -eo pipefail

# 加载配置
CONFIG_FILE=${CONFIG_FILE:-$(dirname "$0")/.env}
if [ -f "$CONFIG_FILE" ]; then
    source "$CONFIG_FILE"
fi

# 必需配置检查
: ${HARBOR_URL:?必须设置HARBOR_URL环境变量或配置}
: ${HARBOR_ADMIN_USER:?必须设置HARBOR_ADMIN_USER环境变量或配置}
: ${HARBOR_ADMIN_PASSWORD:?必须设置HARBOR_ADMIN_PASSWORD环境变量或配置}

# 默认配置
DRY_RUN=${DRY_RUN:-false}
DELETE_UNTAGGED=${DELETE_UNTAGGED:-true}
SCHEDULE_TYPE=${SCHEDULE_TYPE:-"Daily"}
SCHEDULE_CRON=${SCHEDULE_CRON:-"0 0 2 * * *"}

# 基础认证
AUTH_HEADER="Authorization: Basic $(echo -n "${HARBOR_ADMIN_USER}:${HARBOR_ADMIN_PASSWORD}" | base64)"

# 配置定时垃圾回收
configure_scheduled_gc() {
  echo "$(date '+%Y-%m-%d %T') - 开始配置Harbor垃圾回收计划..."

  local response=$(curl -s -k -X PUT "https://${HARBOR_URL}/api/v2.0/system/gc/schedule" \
    -H "$AUTH_HEADER" \
    -H "Content-Type: application/json" \
    -d '{
      "schedule": {
        "type": "'"${SCHEDULE_TYPE}"'",
        "cron": "'"${SCHEDULE_CRON}"'"
      },
      "delete_untagged": '"${DELETE_UNTAGGED}"',
      "dry_run": '"${DRY_RUN}"'
    }')

  # 检查响应
  if echo "$response" | grep -q '"message":'; then
    echo "$(date '+%Y-%m-%d %T') - 错误: $(echo "$response" | jq -r '.message')" >&2
    exit 1
  fi

  echo "$(date '+%Y-%m-%d %T') - 成功配置${SCHEDULE_TYPE}垃圾回收计划，时间: ${SCHEDULE_CRON}"
  echo "$(date '+%Y-%m-%d %T') - 删除未标记镜像: ${DELETE_UNTAGGED}, 模拟运行: ${DRY_RUN}"
}

# 主执行
configure_scheduled_gc
